package com.easy.controller;

import com.easy.bean.User;

import com.easy.common.CommonResult;
import com.easy.service.IUser;
import com.easy.util.JWTUtil;
import com.easy.util.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;


@RestController
@CrossOrigin
public class UserController {
    @Autowired
    IUser userD;

    @PostMapping("dologin")
    public CommonResult doLogin(User user){
        String token=userD.doLogin(user);
        if(token==null){
            return CommonResult.fail(403,"登录失败");
        }else{
            return CommonResult.success(200,"登陆成功",token);
        }
    }
    @GetMapping("checktoken")
    public CommonResult checkToken(HttpServletRequest request){
        String token=request.getHeader("Authorization");
        if(token!=null&& JWTUtil.verifyToken(token)){
            return CommonResult.success();
        }
        return CommonResult.fail();
    }

    @GetMapping("testpassword")
    public CommonResult testPassword(User user){
        boolean test=userD.getUserByUsername(user);
        return CommonResult.success(test);
    }

    @PutMapping("editpassword")
    public  CommonResult editPassword(User user){
        userD.editUser(user);
        return CommonResult.success();
    }
    //查询
    @GetMapping("searchuser")
    public CommonResult searchUser(User user, Page page){
        List<User> list=userD.searchUser(user,page);
        int count=userD.getCount(user);
        HashMap map=new HashMap();
        map.put("list",list);
        map.put("count",count);
        return CommonResult.success(map);
    }

    @PostMapping("addUser")
    public CommonResult addUser(@RequestBody User user){
        userD.addUser(user);
        user=userD.getUser(user.getId());
        return CommonResult.success(user);
    }

}
